package com.gpj.learn.springcloud.ribbon.loadbalanced.config;

import com.gpj.learn.springcloud.ribbon.loadbalanced.annotations.CustomLoadBalanced;
import com.gpj.learn.springcloud.ribbon.loadbalanced.interceptor.CustomLoadBalancerInterceptor;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @className CustomLoadBalancedConfiguration
 * @description
 *   TODO
 * @author GPJ
 * @date 2021/9/27 18:12
 * @version 1.0
 **/
@Configuration
public class CustomLoadBalancedConfiguration {
	@CustomLoadBalanced
	@Autowired(required = false)
	private List<RestTemplate> restTemplates;

	@Bean
	public CustomLoadBalancerInterceptor customLoadBalancerInterceptor(LoadBalancerClient loadBalancerClient){
	    return new CustomLoadBalancerInterceptor(loadBalancerClient);
	}

	/**
	 * SmartInitializingSingleton -- SpringBoot的扩展点,
	 * 当spring中的全部单例Bean都被创建并初始化完毕后,
	 * 会调用SmartInitializingSingleton#afterSingletonsInstantiated()
	 */
	@Bean
	public SmartInitializingSingleton customLoadBalancedRestTemplateInitializer(CustomLoadBalancerInterceptor customLoadBalancerInterceptor) {
		return () -> {
			if(restTemplates == null || restTemplates.size() < 1) return;

			for (RestTemplate restTemplate : restTemplates) {
				List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
				// 填充拦截器
				interceptors.add(customLoadBalancerInterceptor);
			}
		};
	}
}
